package com.lb.algorithm;

/**
 * @version 1.0
 * @Author: Edward
 * @Date: 2021/10/8 18:48
 * @Description:
 */
public class MergeSort {
    public static void main(String[] args) {
        int[] arr = {1,4,7,8,3,6,9};
        sort(arr,0, arr.length - 1);

        print(arr);
    }

    public static void sort(int[] arr, int left, int right) {
        if (left == right) {
            return;
        }
        int mid = left + (right - left) / 2;

        //左边排序
        sort(arr, left, mid);

        //右边排序
        sort(arr, mid+1, right);

        // 合并
        merge(arr, left, mid + 1, right);

//        merge(arr, 0, 4, arr.length - 1);
//        merge(arr, 1, 4, 5);
    }

    static void merge(int[] arr, int leftPtr, int rightPtr, int rightBound) {
//        int mid = arr.length >> 1;
        int mid = rightPtr - 1;
        int[] temp = new int[rightBound - leftPtr + 1];

        int i = leftPtr;
        int j = rightPtr;
        int k = 0;

        while (i <= mid && j <= rightBound) {
            temp[k++] = arr[i] <= arr[j] ? arr[i++] : arr[j++];
        }

        while (i <= mid) {
            temp[k++] = arr[i++];
        }

        while (j <= rightBound) {
            temp[k++] = arr[j++];
        }

        for (int l = 0; l < temp.length; l++) {
            arr[leftPtr + l] = temp[l];
        }
//        print(temp);
    }

    static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = arr[i];
    }

    static void print(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}
